package cn.yotta.user.api.feign.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author yotta
 * @date 2023/4/4 9:25
 * feign请求上下文拦截器，设置登录cookie等
 */
public class FeignContextInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(requestAttributes)) {
            return;
        }
        // 追加cookie
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        if (request.getCookies() != null) {
            List<String> cookies = new ArrayList<>(request.getCookies().length);
            for (Cookie cookie : request.getCookies()) {
                final String name = cookie.getName();
                final String value = cookie.getValue();
                cookies.add(name + "=" + value);
            }
            // 添加cookie
            requestTemplate.header("Cookie", StringUtils.join(cookies, ';'));
        }
    }
}
